package com.jsmtr.rms.controller.writtentest;

import com.jsmtr.rms.entity.KnowManage;
import com.jsmtr.rms.entity.Knowledge;
import com.jsmtr.rms.entity.LimitRequest;
import com.jsmtr.rms.entity.ResponseBuilder;
import com.jsmtr.rms.service.IKnowledgeManageService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.jsmtr.rms.entity.ResponseBuilder.simpleResponse;
import static com.jsmtr.rms.service.impl.KnowledgeManageServiceImpl.DISABLED;
import static com.jsmtr.rms.service.impl.KnowledgeManageServiceImpl.ENABLED;

/**
 * @author wyh
 */
@Controller
@RequestMapping("/KnowledgeManager")
public class KnowledgeManageController {
    @Resource
    IKnowledgeManageService knowledgeManageService;

    @RequestMapping(value = "/")
    public String knowledgeManager(Model model) {
        try {
            model.addAttribute("jobs", knowledgeManageService.getJobs());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "exam/knowlegPoints";
    }

    @RequestMapping("/addKnowledgeFrame/")
    public String addKnowledgeFrame() {
        return "exam/addKnowledge";
    }

    @RequestMapping("/editKnowledgeFrame/")
    public String editKnowledgeFrame() {
        return "exam/editKnowledge";
    }

    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/getKnowledgeList", method = RequestMethod.POST)
    public void getKnowledgeList(HttpServletResponse response, @RequestBody LimitRequest limitRequest) {
        String position = null;
        String knowledgeState = null;
        String keyWord = null;
        int curPage = limitRequest.getPage();
        int pageSize = limitRequest.getLimit();
        Map<String, Object> search = limitRequest.getSearch();
        if (search != null) {
            position = (String) search.get("jname");
            knowledgeState = (String) search.get("state");
            keyWord = (String) search.get("key");
        }
        String orderKey = limitRequest.getOrderKey();
        String orderType = limitRequest.getOrderType();
        ResponseBuilder responseBuilder = new ResponseBuilder();
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            Map<String, Object> knowManagerMap = knowledgeManageService.getKnowledgeList(curPage, pageSize, position,
                    knowledgeState, keyWord, orderKey, orderType);
            Long count = (Long) knowManagerMap.get("count");
            List<KnowManage> data = (List<KnowManage>) knowManagerMap.get("data");
            String dataS = JSONArray.fromObject(data).toString();
            writer.write(responseBuilder.setPage(curPage, Math.toIntExact(count)).setData(dataS).build());
        } catch (Exception e) {
            e.printStackTrace();
            Objects.requireNonNull(writer).write(responseBuilder.setStatus(ResponseBuilder.ERROR)
                    .setMsg(ResponseBuilder.ERROR_STR).removePage().build());
        }
    }

    @RequestMapping(value = "/addKnowledge", method = RequestMethod.POST)
    public void addKnowledge(String knowledgeName, String position, @RequestBody List<Knowledge> knowledge, HttpServletRequest request,
                             HttpServletResponse response) {
        simpleResponse(knowledgeManageService.addKnowledge(knowledge, knowledgeName, position, request), response);
    }

    @RequestMapping(value = "/editKnowledge", method = RequestMethod.POST)
    @ResponseBody
    public void editKnowledge(String knowledgeName, String position, @RequestBody List<Knowledge> knowledge, HttpServletResponse response) {
        simpleResponse(knowledgeManageService.editKnowledge(knowledge, knowledgeName, position), response);
    }

    @RequestMapping(value = "/enableKnowledge", method = RequestMethod.POST)
    @ResponseBody
    public void enableKnowledge(String id, Boolean enable, HttpServletResponse response, HttpServletRequest request) {
        simpleResponse(knowledgeManageService.enableKnowledge(id, enable ? ENABLED : DISABLED, request), response);
    }

    @RequestMapping(value = "/deleteKnowledge", method = RequestMethod.POST)
    public void deleteKnowledge(String id, HttpServletResponse response) {
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            boolean success = knowledgeManageService.deleteKnowledge(id);
            writer.write(Boolean.toString(success));
        } catch (Exception e) {
            e.printStackTrace();
            Objects.requireNonNull(writer).write(Boolean.FALSE.toString());
        }
    }

    @RequestMapping(value = "/seeKnowledge", method = RequestMethod.POST)
    @ResponseBody
    @SuppressWarnings({"unchecked", "rawtypes"})
    public void seeKnowledge(@RequestBody LimitRequest lRequest, HttpServletResponse response) {
        ResponseBuilder responseBuilder = new ResponseBuilder();
        PrintWriter writer = null;
        try {
            writer = response.getWriter();

            int curPage = lRequest.getPage();
            int limit = lRequest.getLimit();
            Map<String, Object> knowledgeQueryResult = knowledgeManageService.getKnowledgePointList(curPage, limit, lRequest.getSearch());
            List knowledgeList = (List) knowledgeQueryResult.get("data");
            Long count = (Long) knowledgeQueryResult.get("count");
            List json = (List) knowledgeList.stream().map(d -> {
                JSONObject jsonObject = JSONObject.fromObject(((Object[]) d)[0]);
                jsonObject.put("kname", ((Object[]) d)[1]);
                return  jsonObject.toString();
            }).collect(Collectors.toList());
            //String dataS = JSONArray.fromObject(knowledgeList).toString();
            String dataS = JSONArray.fromObject(json).toString();
            writer.write(responseBuilder.setPage(curPage, Math.toIntExact(count)).setData(dataS).build());
        } catch (Exception e) {
            e.printStackTrace();
            Objects.requireNonNull(writer).write(responseBuilder.setStatus(ResponseBuilder.ERROR)
                    .setMsg(ResponseBuilder.ERROR_STR).removePage().build());
        }
    }
}
